package com.todo.pro.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.todo.pro.entity.BaiduApp;
import com.todo.pro.handle.EE;
import com.todo.pro.jwt.JwtUtil;
import com.todo.pro.res.JsonResult;
import com.todo.pro.res.model.BaiduAppResult;
import com.todo.pro.service.BaiduAppService;
import com.todo.pro.util.MapUtil;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.util.NumberUtil;

/**
 * @author SiZhongxia
 * @since 2017-12-27
 */
@Controller
@RequestMapping("baiduApp")
public class BaiduAppController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(BaiduAppController.class);

	@Autowired
	private BaiduAppService baiduAppService;

	@RequiresAuthentication
	@RequestMapping(value = "list")
	public ModelAndView list(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("modules/baiduApp/list");
		mav.addObject("csrftoken",
				JwtUtil.createToken(MapUtil.init().putVal("path", "gq-baiduApp-list"), 2L * 60 * 60 * 1000));
		return mav;
	}

	@ResponseBody
	@RequiresAuthentication
	@RequestMapping(value = "data")
	public JsonResult<List<BaiduAppResult>> data(HttpServletRequest request) {
		Wrapper<BaiduApp> baiduAppWrapper = new EntityWrapper<>();
		String keyword = request.getParameter("keyword");
		if (StringUtils.isNotBlank(keyword)) {
			baiduAppWrapper.like("app_name", keyword);
		}
		baiduAppWrapper.orderBy("create_time", false);
		List<BaiduApp> baiduApps = baiduAppService.selectList(baiduAppWrapper);
		List<BaiduAppResult> baiduApprs = new ArrayList<>();
		int count = baiduApps.size();
		if (count > 0) {
			for (BaiduApp baiduApp : baiduApps) {
				BaiduAppResult baiduAppr = new BaiduAppResult();
				BeanUtils.copyProperties(baiduApp, baiduAppr);
				baiduAppr.setId(baiduApp.getId().toString());
				baiduApprs.add(baiduAppr);
			}
		}
		return new JsonResult<List<BaiduAppResult>>(count, baiduApprs);
	}

	@ResponseBody
	@RequiresAuthentication
	@RequestMapping(value = "alls")
	public JsonResult<List<Map<String, String>>> alls(HttpServletRequest request) {
		Wrapper<BaiduApp> baiduAppWrapper = new EntityWrapper<>();
		String keyword = request.getParameter("keyword");
		if (StringUtils.isNotBlank(keyword)) {
			baiduAppWrapper.like("app_name", keyword);
		}
		baiduAppWrapper.orderBy("create_time", false);
		List<BaiduApp> baiduApps = baiduAppService.selectList(baiduAppWrapper);
		List<Map<String, String>> baiduApprs = new ArrayList<>();
		int count = baiduApps.size();
		if (count > 0) {
			for (BaiduApp baiduApp : baiduApps) {
				Map<String, String> baiduAppr = new HashMap<String, String>();
				baiduAppr.put("value", baiduApp.getId().toString());
				baiduAppr.put("name", baiduApp.getAppName());
				baiduApprs.add(baiduAppr);
			}
		}
		return new JsonResult<List<Map<String, String>>>(baiduApprs);
	}

	@ResponseBody
	@RequiresAuthentication
	@RequestMapping(value = "changeusedstatus")
	public JsonResult<Object> changeusedstatus(HttpServletRequest request) {
		String id = request.getParameter("id");
		if (StringUtils.isBlank(id)) {
			return new JsonResult<Object>(false, EE.INVALID_PARAMETERS.i());
		}
		String used = request.getParameter("used");
		if (!NumberUtil.isInteger(used)) {
			return new JsonResult<Object>(false, EE.INVALID_PARAMETERS.i());
		}

		BaiduApp baiduApp = baiduAppService.selectById(id);
		if (baiduApp == null) {
			return new JsonResult<Object>(false, EE.INVALID_PARAMETERS.i());
		}
		baiduApp.setUsed(new Integer(used));
		baiduApp.setUpdateTime(DateUtil.date());
		if (!baiduAppService.updateById(baiduApp)) {
			return new JsonResult<Object>(false, EE.ERR_FOR_WAIT.i());
		}

		return new JsonResult<Object>(true, EE.SUCCESS_OP.i());
	}

	@ResponseBody
	@RequiresAuthentication
	@RequestMapping(value = "updateField")
	public JsonResult<Object> updateField(HttpServletRequest request) {
		String csrftoken = request.getParameter("csrftoken");
		if (StringUtils.isBlank(csrftoken)) {
			return new JsonResult<Object>(false, EE.ERROR_FORM.i());
		}
		Map<String, Object> jwtData = JwtUtil.parseJWT(csrftoken);
		if (jwtData == null) {
			return new JsonResult<Object>(false, EE.ERROR_FORM_OVERDUE.i());
		}

		if (!"gq-baiduApp-list".equals(jwtData.get("path"))) {
			return new JsonResult<Object>(false, EE.ERROR_FORM.i());
		}

		String id = request.getParameter("id");
		if (StringUtils.isBlank(id)) {
			return new JsonResult<Object>(false, EE.INVALID_PARAMETERS.i());
		}

		String field = request.getParameter("field");
		if (StringUtils.isBlank(field)) {
			return new JsonResult<Object>(false, EE.ERROR_FORM.i());
		}

		String value = request.getParameter("value");
		if (StringUtils.isBlank(value)) {
			value = "";
		}

		BaiduApp baiduApp = baiduAppService.selectById(id);
		if (baiduApp == null) {
			return new JsonResult<Object>(false, EE.INVALID_PARAMETERS.i());
		}
		if ("appName".equals(field)) {
			baiduApp.setAppName(value);
		} else if ("appId".equals(field)) {
			baiduApp.setAppId(value);
		} else if ("appKey".equals(field)) {
			baiduApp.setAppKey(value);
		} else if ("secretKey".equals(field)) {
			baiduApp.setSecretKey(value);
		} else {
			return new JsonResult<Object>(false, EE.ERROR_FORM.i());
		}
		baiduApp.setUpdateTime(DateUtil.date());
		if (!baiduAppService.updateById(baiduApp)) {
			return new JsonResult<Object>(false, EE.ERR_FOR_WAIT.i());
		}

		return new JsonResult<Object>(true, EE.SUCCESS_OP.i());
	}

	@RequiresAuthentication
	@RequestMapping(value = "add")
	public ModelAndView add(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("modules/baiduApp/add");
		mav.addObject("csrftoken",
				JwtUtil.createToken(MapUtil.init().putVal("path", "gq-baiduApp-add"), 30L * 60 * 1000));
		return mav;
	}

	@ResponseBody
	@RequiresAuthentication
	@RequestMapping(value = "save")
	public JsonResult<Object> save(HttpServletRequest request) {
		String csrftoken = request.getParameter("csrftoken");
		if (StringUtils.isBlank(csrftoken)) {
			return new JsonResult<Object>(false, EE.ERROR_FORM.i());
		}
		Map<String, Object> jwtData = JwtUtil.parseJWT(csrftoken);
		if (jwtData == null) {
			return new JsonResult<Object>(false, EE.ERROR_FORM_OVERDUE.i());
		}

		if (!"gq-baiduApp-add".equals(jwtData.get("path"))) {
			return new JsonResult<Object>(false, EE.ERROR_FORM.i());
		}
		String appName = request.getParameter("appName");
		if (StringUtils.isBlank(appName)) {
			return new JsonResult<Object>(false, EE.ERROR_FORM.i());
		}
		String appId = request.getParameter("appId");
		if (StringUtils.isBlank(appId)) {
			return new JsonResult<Object>(false, EE.ERROR_FORM.i());
		}
		String appKey = request.getParameter("appKey");
		if (StringUtils.isBlank(appKey)) {
			return new JsonResult<Object>(false, EE.ERROR_FORM.i());
		}
		String secretKey = request.getParameter("secretKey");
		if (StringUtils.isBlank(secretKey)) {
			return new JsonResult<Object>(false, EE.ERROR_FORM.i());
		}

		BaiduApp baiduApp = new BaiduApp();
		baiduApp.setAppName(appName);
		baiduApp.setAppId(appId);
		baiduApp.setAppKey(appKey);
		baiduApp.setSecretKey(secretKey);
		baiduApp.setUsed(0);
		baiduApp.setCreateTime(DateUtil.date());
		baiduApp.setUpdateTime(DateUtil.date());
		if (!baiduAppService.insert(baiduApp)) {
			return new JsonResult<Object>(false, EE.ERR_FOR_WAIT.i());
		}

		return new JsonResult<Object>(true, EE.SUCCESS_OP.i());
	}

	@ResponseBody
	@RequiresAuthentication
	@RequestMapping(value = "delete")
	public JsonResult<Object> delete(HttpServletRequest request) {
		String csrftoken = request.getParameter("csrftoken");
		if (StringUtils.isBlank(csrftoken)) {
			return new JsonResult<Object>(false, EE.ERROR_FORM.i());
		}
		Map<String, Object> jwtData = JwtUtil.parseJWT(csrftoken);
		if (jwtData == null) {
			return new JsonResult<Object>(false, EE.ERROR_FORM_OVERDUE.i());
		}

		if (!"gq-baiduApp-list".equals(jwtData.get("path"))) {
			return new JsonResult<Object>(false, EE.ERROR_FORM.i());
		}

		String[] ids = request.getParameterValues("ids[]");
		if (ids == null || ids.length == 0) {
			return new JsonResult<Object>(false, EE.SELECT_LEAST_ONE_RECORD.i());
		}

		Set<Long> deleteLoginPicIds = new HashSet<>();
		for (String baiduAppId : ids) {
			deleteLoginPicIds.add(new Long(baiduAppId));
		}

		if (!baiduAppService.deleteBatchIds(deleteLoginPicIds)) {
			return new JsonResult<Object>(false, EE.ERR_FOR_WAIT.i());
		}

		return new JsonResult<Object>(true, EE.SUCCESS_OP.i());
	}

}
